// user/order/info.js
var home = require("../../utils/util.js");
var url = home.home;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked:false,
    show:false,//展示优惠券弹出层
    active:0,//标签页下标
    checked2:false,//不使用
    activeNames:0,
    goodsData:[],//商品数据
    goodsPrice:0,//商品价格
    countPrice:0,//合计
    discount:home.getKey('discount'),//折扣比例
    does:0,//优惠券
    doesMoney:0,//优惠金额
    doesData:[],//可用优惠券数据
    doesData2:[],//不可用优惠券数据
    doesGroup:[],//选择的优惠券集合
    gbMoney:200,//股本余额
    userMoney:300,//会员余额
    doesTitle:'',
    page:1,
    storeId:home.getKey('storeId'),
    memberId:home.getKey('userId'),//会员id
    show9:1,
    content:'',//留言
    doesDataLen:0,
    doesDataLen2:0,
    couponLists:[],
    isSeleteData:[],
    videoData: {
      direction: -90,
      show_mute_btn: false,
      vslide_gesture: false,
    },
    btnState: true,
    totalCanUseDiscountAmount:0,
    bgcolor: home.getKey('bgcolor'),
  },

  //留言
  onContent(e){
    this.setData({content:e.detail});
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goodsData = options.data;
    goodsData = JSON.parse(goodsData);
    console.log('----------------------');
    console.log(goodsData);
    console.log('----------------------');
    let goodsPrice = 0;
    for (let i = 0; i < goodsData.length; i++) {
      goodsPrice += goodsData[i].price * goodsData[i].qty;
      goodsData[i].totalPrice = goodsData[i].price * goodsData[i].qty;
      goodsData[i].discountAmount = 0;
    }
    this.setData({
      goodsPrice:goodsPrice,
      countPrice:goodsPrice,
      goodsData:goodsData
    });
  },

  //计算价格
  getPrice(){
    let that = this;
    let commodityList = [];
    for (let i = 0; i < this.data.goodsData.length; i++) {
      let json = {};
      if(this.data.goodsData[i].goodsId != null){
        json.id = this.data.goodsData[i].goodsId
      }
      else{
        if (this.data.goodsData[i].type == 1) {
          json.id = this.data.goodsData[i].commodityId;
        } else {
          json.id = this.data.goodsData[i].projectId;
        }
      }
      
      //console.log(this.data.goodsData[i]);
      
      json.type = this.data.goodsData[i].type;
      json.count = this.data.goodsData[i].qty;
      commodityList.push(json);
    }
    wx.request({
      url: url + 'app/compute',
      data: {
        storeId:home.getKey('storeId'),
        memberId:home.getKey('userId'),
        useMemberDiscount:that.data.checked ? '1' : '0',
        memberDiscount:that.data.discount,
        commodityList:commodityList,
        couponList:that.data.couponLists
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        console.log(res.data);
        if (res.data.code == 200) {
          for (let i = 0; i < that.data.goodsData.length; i++) {
            for (let j = 0; j < res.data.result.commodityList.length; j++) {
              if (that.data.goodsData[i].type == 2) {
                if (that.data.goodsData[i].projectId == res.data.result.commodityList[j].id) {
                  res.data.result.commodityList[j].specification = that.data.goodsData[i].commoditySpec;
                }
              }
            }
          }
          that.setData({
            goodsPrice:res.data.result.totalAmount,
            countPrice:res.data.result.realAmount,
            doesMoney:res.data.result.totalDiscountAmount,
            commodityLists:res.data.result.commodityList,
            totalCanUseDiscountAmount: res.data.result.totalCanUseDiscountAmount
          })
          that.getVipCardList();
        } else {
          home.wxMessage('优惠券获取失败','none');
        }
      }
    });
  },

  //查询优惠券列表
  getVipCardList(){
    let that = this;
    wx.request({
      url: url + 'app/listCoupon',
      data:{
        memberId:home.getKey('userId'),
        storeId:home.getKey('storeId'),
        totalCanUseDiscountAmount:that.data.totalCanUseDiscountAmount,
        useMemberDiscount:that.data.checked,
        couponList:that.data.couponLists,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          let doesData2 = [];
          let doesData = [];
          let isSeleteData = [];
          for (let i = 0; i < res.data.result.length; i++) {
            res.data.result[i].types = 2;
            if (res.data.result[i].videos) {
              let index = res.data.result[i].videos.indexOf('.',1);
              if (res.data.result[i].videos.substr(index+1) == 'mp4' || res.data.result[i].videos.substr(index+1) == 'MP4') {
                res.data.result[i].types = 1;
                res.data.result[i].videos = 'https://kyz.fbhkj.com/' + res.data.result[i].videos;
              } else {
                res.data.result[i].videos = 'https://kyz.fbhkj.com//' + res.data.result[i].videos;
              }
            }
            res.data.result[i].nums = 1;
            res.data.result[i].isUse = true;
            if (res.data.result[i].isSelect == '1') {
              isSeleteData.push(res.data.result[i].id);
            }
            if (res.data.result[i].disabled == true) {
              doesData2.push(res.data.result[i]);
            } else {
              doesData.push(res.data.result[i]);
            }
          }
          that.setData({
            doesData:doesData,
            doesData2:doesData2,
            show9:doesData.length > 0 ? 1 : 2,
            show10:doesData2.length > 0 ? 1 : 2,
            doesDataLen:doesData.length,
            doesDataLen2:doesData2.length,
            isSeleteData:isSeleteData
          })
        } else {
          home.wxMessage('获取优惠券失败,请稍后再试','none');
        }
      }
    })
  },

  //下单
  saveOrder(){
    wx.showLoading({
      title: '加载中...',
    });
    this.setData({
      btnState: false
    });
    let that = this;
    let goodsData = this.data.goodsData;
    let couponList = [];
    for (let i = 0; i < this.data.doesData.length; i++) {
      for (let j = 0; j < this.data.couponLists.length; j++) {
        if (this.data.couponLists[j].id == this.data.doesData[i].id) {
          couponList.push(this.data.doesData[i]);
        }
      }
    }
    wx.request({
      url: url + 'app/saveOrder',
      data:{
        storeId:home.getKey('storeId'),//店铺id
        memberId:home.getKey('userId'),//会员id
        useMemberDiscount:that.data.checked ? 1 : 0,//是否使用折扣
        memberDiscount:that.data.discount,//会员折扣比例
        remark:that.data.content,//留言备注
        totalAmount:that.data.goodsPrice,//总金额
        totalDiscountAmount:that.data.doesMoney,//优惠金额
        realAmount:that.data.countPrice,//实际金额
        commodityList:that.data.commodityLists,//商品列表
        couponList:couponList
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          wx.hideLoading({
            success: (res) => {
              that.setData({
                btnState: true,
              })
            },
          })
          goodsData = JSON.stringify(res.data.result);
          wx.redirectTo({
            url: './complate?goodsData='+encodeURIComponent(goodsData),
          });
        } else {
          wx.showToast({
            title: '发生错误',
            icon: 'none'
          })
        }
      }
    })
  },

  //滑动tabs
  ontabs(e){

  },

  //展示优惠券弹出层
  showPopup() {
    this.setData({ show: true });
  },

  //关闭优惠券弹出层
  onClose() {
    let doesTitle = [];
    for (let i = 0; i < this.data.doesData.length; i++) {
      if (this.data.doesGroup.indexOf(this.data.doesData[i].id.toString()) > -1) {
        doesTitle.push(this.data.doesData[i].ticketName);
      }      
    }
    this.setData({ show: false,doesTitle:doesTitle.join(',') });
  },

  /**
   * 跳转订单结算
   */
  toAgainst(){
    wx.navigateTo({
      url: './against',
    })
  },

  /**
   * 选择折扣
   */
  onCheck(e){
    //可与其他优惠券叠加使用isSelect = 1
    //可自身叠加使用isSelectNext = 1
    let checked = this.data.checked;
    let couponLists = [];
    let doesTitle = [];
    let doesGroup = [];
    for (let i = 0; i < this.data.doesData.length; i++) {
      for (let j = 0; j < this.data.couponLists.length; j++) {
        if (this.data.doesData[i].ticketType == '1' && this.data.doesData[i].id == this.data.couponLists[j].id) {
          couponLists.push(this.data.couponLists[j]);
          doesTitle.push(this.data.doesData[i].ticketName);
          doesGroup.push(this.data.doesData[i].id.toString());
        }
      }
    }
    this.setData({
      checked: !checked,
      couponLists:couponLists,
      doesTitle: doesTitle.length > 0 ? doesTitle.join(',') : '',
      doesGroup:doesGroup,
    });
    this.getPrice();
  },

  //点击不使用优惠券
  onCheck2(e){
    let checked2 = this.data.checked2;
    let doesGroup = this.data.doesGroup;
    if (!checked2) {
      doesGroup = [];
    }
    let goodsData = this.data.goodsData;
    for (let i = 0; i < goodsData.length; i++) {
      goodsData[i].discountMoney = 0;
      goodsData[i].discountAmount = 0;
    }
    this.setData({
      checked2: !checked2,
      doesGroup:doesGroup,
      goodsData:goodsData,
      couponLists:[],
    });
    this.getPrice();
  },

  //点击优惠券复选框
  onDoesCheck(e){
    let that = this;
    let couponLists = [];
    let doesData = this.data.doesData;
    let item = {};
    let checked = this.data.checked;
    for (let i = 0; i < doesData.length; i++) {
      if (e.detail[e.detail.length - 1] == doesData[i].id) {
        item = doesData[i];
      }
      if (e.detail[e.detail.length - 1] == doesData[i].id && doesData[i].ticketType != '1') {
        checked = false;
      }
      if (e.detail[e.detail.length - 1] == doesData[i].id && doesData[i].ticketType != '1' && doesData[i].isSelect == '0') {
        checked = false;
      }
    }
    //选择的优惠券中存在不可叠加
    let jj = e.detail.filter(function(val){return that.data.isSeleteData.indexOf(val) > -1});
    let id = '';
    for (let i = 0; i < doesData.length; i++) {
      let json = {};
      json.id = doesData[i].id;
      json.num = doesData[i].nums;
      json.ticketType = doesData[i].ticketType;
      if (jj.length > 0) {
        if (jj.indexOf(doesData[i].id.toString()) > -1) {
          e.detail = [];
          e.detail.push(doesData[i].id);
          couponLists.push(json);
          doesData[i].isUse = true;
        } else {
          doesData[i].isUse = false;
        }
      } else {
        doesData[i].isUse = true;
        if (e.detail.indexOf(doesData[i].id.toString()) > -1) {
          couponLists.push(json);
          if (item.ticketType != '1') {
            let index = -1;
            for (let j = 0; j < couponLists.length; j++) {
              if (couponLists[j].id != item.id && couponLists[j].ticketType != '1') {
                index = j;
                id = couponLists[j].id;
              }
            }
            if (index > -1) {
              couponLists.splice(index,1);
              if (id != '') {
                e.detail.splice(e.detail.indexOf(id),1);
              }
            }
          }
        }
      }
    }
    this.setData({
      doesGroup:e.detail,
      doesData:doesData,
      couponLists:couponLists,
      checked:checked,
      checked2:false,
    });
    this.getPrice();
  },

  //步进器
  onste(e){
    let doesId = e.currentTarget.dataset.id;
    let doesData = this.data.doesData;
    let does = 0;
    let doesGroup = this.data.doesGroup;
    for (let i = 0; i < doesData.length; i++) {
      if (doesId == doesData[i].id) {
        doesData[i].nums = Number(e.detail);
        console.log(Number(e.detail));
      }
      // if (doesGroup.indexOf(doesData[i].id.toString()) > -1) {
      //   console.log(doesData[i].price);
      //   does += doesData[i].nums * doesData[i].price;
      // }
    }
    let countPrice = this.data.goodsPrice;
    // if (doesGroup.indexOf(doesId.toString()) > -1) {
    //   countPrice -= does;
    // }
    this.setData({
      doesData:doesData,
      countPrice:countPrice,
      does:does,
      doesMoney:does
    })
  },

  onColl(e){
    this.setData({
      activeNames: e.detail,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      discount:home.getKey('discount')
    })
    this.getPrice();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})